package com.example.springblog.controller;

import com.example.springblog.model.BlogInfo;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.BlogService;
import com.example.springblog.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;


    //获取博客列表
    @RequestMapping("/getlist")
    public List<BlogInfo> getBlogList(){
        return blogService.getBlogList();
    }

    //获取博客详情
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId,HttpServletRequest request){
        //判断登录用户和作者是否是同一人，决定了是否显示删除，和编辑

        BlogInfo blogInfo = blogService.getBlogDetail(blogId);
        //通过获取到userId ，和blogId进行比较
        String jwtToken = request.getHeader("user_token");
        Integer userId = JWTUtils.getUserIdFromToken(jwtToken);

        if(userId!=null && blogInfo.getUserId()==userId){
            blogInfo.setLoginUser(1);
        }
        return blogInfo;
    }

    //发布一篇博客
    @RequestMapping("/add")
    public boolean insertBlog(String title,String content,HttpServletRequest request){
        System.out.println("title的值:"+title);
        //从header中获取token
        String jwtToken = request.getHeader("user_token");
        //获取一下UserId
        Integer userId = JWTUtils.getUserIdFromToken(jwtToken);
        if(!StringUtils.hasLength(title) || !StringUtils.hasLength(content)){
            return false;
        }
        BlogInfo blogInfo = new BlogInfo(title,content,userId);
        //进行发布
        blogService.insertBlog(blogInfo);
        return true;
    }


    //修改博客
    @RequestMapping("/update")
    public Result update(@RequestBody BlogInfo blogInfo){
        blogService.updateBlog(blogInfo);
        return Result.success(true);
    }

    //删除博客
    @RequestMapping("/delete")
    public boolean deleteBlog(Integer blogId){
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setDeleteFlag(1);
        blogInfo.setId(blogId);

        blogService.updateBlog(blogInfo);
        return true;
    }
}
